<?php
// -------------------------------excel表格下载----------------------------------

excel下载：
      github   https://github.com/PHPOffice/PHPExcel
      使用 Classes 目录引入

推荐示例：
      http://www.oschina.net/code/snippet_112754_15765
      https://jingyan.baidu.com/article/915fc414f4c2e451384b205c.html





getExcel('excel', [
    '学号', '姓名', '性别', '年龄', '班级'
], [
    ['1', '小，,,,ssss,,www,王', '男', '20', '100'],
    ['2', '小李', '男', '20', '101'],
    ['3', '小张', '女', '20', '102'],
    ['4', '小赵', '女', '20', '103']
]);

/**
 * excel 下载：github   https://github.com/PHPOffice/PHPExcel
 * 示例：http://www.oschina.net/code/snippet_112754_15765
 * @param $fileName string 文件名
 * @param $headArr array 标题
 * @param $data array 数据
 */
function getExcel($fileName = 'excel', $headArr, $data)
{
    // 配置
    error_reporting(E_ALL);
    set_time_limit(0);
    date_default_timezone_set('PRC');
    $excel_dir = $_SERVER['DOCUMENT_ROOT'] . '/Classes/';// 根目录（实际环境中注意修改目录）

    // 默认加载无需修改
    include $excel_dir . 'PHPExcel.php';
    require_once $excel_dir . 'PHPExcel/Reader/Excel2007.php';
    require_once $excel_dir . 'PHPExcel/Reader/Excel5.php';
    include_once $excel_dir . 'PHPExcel/IOFactory.php';

    if (empty($data) || !is_array($data)) {
        die("data must be a array");
    }
    if (empty($fileName)) {
        exit;
    }

    //创建新的PHPExcel对象
    $objPHPExcel = new PHPExcel();
    $objProps = $objPHPExcel->getProperties();

    //设置表头
    $key = ord("A");
    foreach ($headArr as $v) {
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $key += 1;
    }

    $column = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();
    foreach ($data as $key => $rows) { //行写入
        $span = ord("A");
        foreach ($rows as $keyName => $value) {// 列写入
            $j = chr($span);
            $objActSheet->setCellValue($j . $column, $value);
            $span++;
        }
        $column++;
    }

    $fileName = iconv("utf-8", "gb2312", $fileName . '.xlsx');
    //重命名表
    $objPHPExcel->getActiveSheet()->setTitle('Simple');
    //设置活动单指数到第一个表,所以Excel打开这是第一个表
    $objPHPExcel->setActiveSheetIndex(0);
    //将输出重定向到一个客户端web浏览器(Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header("Content-Disposition: attachment; filename=\"$fileName\"");
    header('Cache-Control: max-age=0');
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save('php://output'); //文件通过浏览器下载
    // $objWriter->save($fileName); //脚本方式运行，保存在当前目录
    exit;
}






excel('学生excel下载', [
    '学号', '姓名', '性别', '年龄', '班级'
], [
    ['1', '小，,,,ssss,,www,王', '男', '20', '100'],
    ['2', '小李', '男', '20', '101'],
    ['3', '小张', '女', '20', '102'],
    ['4', '小赵', '女', '20', '103']
]);

/**
 * excel 下载：github   https://github.com/PHPOffice/PHPExcel
 * 示例：https://jingyan.baidu.com/article/915fc414f4c2e451384b205c.html
 * @param $filenmae string 文件名
 * @param $title array 标题
 * @param $data array 数据
 */
function excel($filename = 'excel', $title, $data)
{
    // 配置
    error_reporting(E_ALL);
    set_time_limit(0);
    date_default_timezone_set('PRC');
    // 引入excel  此处注意路径
    include $_SERVER['DOCUMENT_ROOT'] . '/Classes/PHPExcel.php';

    // 填充数据
    $excel = new PHPExcel();
    // Excel表格式
    $letter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    //填充表头信息
    for ($i = 0; $i < count($title); $i++) {
        $excel->getActiveSheet()->setCellValue("$letter[$i]1", "$title[$i]");
    }
    //填充表格信息
    // $i 是纵向位置  $j 是横向位置
    $i = 2;
    foreach ($data as $key => $value) {
      $j = 0;
      foreach ($value as $k => $v) {
        $excel->getActiveSheet()->setCellValue("$letter[$j]" . $i, "$v");
        $j++;
      }
      $i++;
    }

    $filename = iconv("utf-8", "gb2312", $filename.'.xls');
    //创建Excel输入对象
    $write = new PHPExcel_Writer_Excel5($excel);
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
    header("Content-Type:application/force-download");
    header("Content-Type:application/vnd.ms-execl");
    header("Content-Type:application/octet-stream");
    header("Content-Type:application/download");;
    header('Content-Disposition:attachment;filename='. $filename);
    header("Content-Transfer-Encoding:binary");
    $write->save('php://output');
    exit;
}







// $json = '[{"hospitalname":"北京协和医院","levelname":"三级甲等"},{"hospitalname":"医科院肿瘤医院","levelname":"三级甲等"},{"hospitalname":"阜外心血管病医院","levelname":"三级甲等"},{"hospitalname":"北京市大兴区妇幼保健院","levelname":"二级甲等"},{"hospitalname":"北京市大兴区人民医院","levelname":"二级甲等"},{"hospitalname":"北京市大兴区红星医院","levelname":"二级综合医院"},{"hospitalname":"北京普祥中医肿瘤医院","levelname":"二级"},{"hospitalname":"北京市仁和医院","levelname":"二级甲等"},{"hospitalname":"中国中医科学院广安门医院南区","levelname":"三级甲等"},{"hospitalname":"北京市大兴区精神病医院","levelname":"二级甲等"}]';

// $data = json_decode($json,true);
// $result = ["医院名字","等级"];
// $filename = "数据表";

// excel($data,$result,$filename);
// function excel($data,$result = '',$filename = '表格'){
// 	if($result){
// 		$result = implode(",",$result)."\r\n";
// 	}
// 	foreach ($data as $key => $value) {
// 		$result .= implode(',',$value)."\r\n";
// 	}
// 	ob_end_clean();
// 	header('Content-Encoding: none');
//       header('Content-Type: application/octet-stream');
//       // header('Content-Type: applicationnd.ms-excel;charset=GB2312');
//       header('Content-Disposition: attachment;filename="'.$filename.'.csv"');
//       header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
//       header("Content-Type: application/force-download");
//       $result = mb_convert_encoding($result, "GB2312", "UTF-8");
//       echo $result;
// }

// // ob_clean();
// //         header('Content-Type: applicationnd.ms-excel;');
// //         header('Content-Disposition: attachment;filename="'.$filename.'.csv"');
// //         header('Cache-Control: max-age=0');
// //         header('Cache-Control: max-age=1');
// //         header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
// //         header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
// //         header ('Cache-Control: cache, must-revalidate');
// //         header ('Pragma: public');
// //         header("Content-Type: application/force-download");
// //         echo $result;       

//     // 导出excel
//     public function excel($filename = '', $title = [], $data = []){
//             if (!$data) {
//                 exit('无数据!');
//             }
//             // 标题
//             if ($title) {
//                 $title = implode(',',$title);
//             } else {
//                 $title = implode(',', array_keys($data[0]));
//             }
//             $result = $title.PHP_EOL;
//             $filename = $filename.date('Y-m-d-H-i-s');
//              foreach ($data as $key => $value) {
//                   $result .= implode(',',$value).PHP_EOL;
//              }
//             ob_clean();
//             header('Content-Type: applicationnd.ms-excel;');
//             header('Content-Disposition: attachment;filename="'.$filename.'.csv"');
//             header('Cache-Control: max-age=0');
//             header('Cache-Control: max-age=1');
//             header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
//             header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
//             header ('Cache-Control: cache, must-revalidate');
//             header ('Pragma: public');
//             header("Content-Type: application/force-download");
//             echo $result;
//             exit;
//     }    

//       // 导出excel
//     public function excel($filename = '', $title = [], $data = []){
//             if (!$data) {
//                 exit('无数据!');
//             }
//             // 标题
//             if ($title) {
//                 $title = implode(',',$title);
//             } else {
//                 $title = implode(',', array_keys($data[0]));
//             }
//             $result = $title.PHP_EOL;
//             $filename = $filename.date('Y-m-d-H-i-s');
//              foreach ($data as $key => $value) {
//                   $result .= implode(',',str_replace(PHP_EOL, ' ', $value)).PHP_EOL;
//              }
//             ob_clean();
//             header( 'Cache-Control: public' );
//             // header('Content-Type: applicationnd.ms-excel;');
//             header("Content-Type:application/msexcel");
//             header('Content-Disposition: attachment;filename="'.$filename.'.csv"');
//             header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');;//内容过期时间 
//             header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');;//标记内容最后修改时间
//             header("Cache-Control: no-cache, must-revalidate" );//强制不缓存
//             header ('Cache-Control: max-age=0');
//             header ('Pragma: public');
//             header("Content-Type: application/force-download");  
//             header("Content-Type: application/octet-stream");  
//             echo $result;
//             exit;
//     }    


